﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CLEXA.ClientTools.Collections;
using CLEXA.DataContracts;
using CLEXA.ServiceContracts;

namespace CLEXA.AdminClient.Cache
{
    public class UserCache : IUserCache
    {
        private readonly IAdminService adminService;
        private readonly ObservableDictionary<int, UserData> users;
        private readonly ReadOnlyObservableDictionary<int, UserData> usersReadOnly;

        public IReadOnlyObservableDictionary<int, UserData> Users
        {
            get { return usersReadOnly; }
        }

        public UserCache(IAdminService adminService)
        {
            this.adminService = adminService;
            this.users = new ObservableDictionary<int, UserData>(this.adminService.GetAllUsers(), p => p.UserId);
            this.usersReadOnly = new ReadOnlyObservableDictionary<int, UserData>(this.users);
        }

        public void CreateUser(string username, string password, bool isActive)
        {
            int id = adminService.CreateUser(username, password, isActive);
            users.Add(id, new UserData(id, username, isActive));
        }

        public void UpdateUser(UserData user)
        {
            UserData old = users[user.UserId];
            adminService.UpdateUser(user);
            users[user.UserId] = old;
        }

        public void DeleteUser(int userId)
        {
            adminService.DeleteUser(userId);
            users.Remove(userId);
        }

        public void ChangeUserPassword(int userId, string password)
        {
            adminService.ChangePassword(userId, password);
        }
    }
}
